/**
 * CollectionTaskListPage
 * 采集任务列表页面
 * Features: 任务列表、创建任务、实时更新、取消/重试
 */

import React, { useState } from 'react'
import { Button, Space } from 'antd'
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons'
import CollectionTaskTable from '@/components/collection/CollectionTaskTable'
import CreateTaskModal from '@/components/collection/CreateTaskModal'
import { useCollectionTaskList, useStartCollectionTask, useCancelCollectionTask, useRetryFailedTables } from '@/hooks/useCollectionTask'

export const CollectionTaskListPage: React.FC = () => {
  const [modalOpen, setModalOpen] = useState(false)

  // 任务列表查询 (带实时轮询)
  const { data, isLoading, refetch } = useCollectionTaskList({})

  // 取消任务
  // 启动任务
  const startMutation = useStartCollectionTask()
  const cancelMutation = useCancelCollectionTask()

  // 重试失败的表
  const retryMutation = useRetryFailedTables()

  const handleStart = (id: number) => {
    startMutation.mutateAsync(id)
  }

  const handleCancel = async (id: number) => {
    await cancelMutation.mutateAsync(id)
  }

  const handleRetry = async (id: number) => {
    await retryMutation.mutateAsync(id)
  }

  const tasks = data?.content || []

  return (
    <div className="p-6">
      <div className="mb-4 flex justify-between items-center">
        <h1 className="text-2xl font-bold">采集任务管理</h1>
        <Space>
          <Button icon={<ReloadOutlined />} onClick={() => refetch()}>
            刷新
          </Button>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setModalOpen(true)}
          >
            创建采集任务
          </Button>
        </Space>
      </div>

      <CollectionTaskTable
        tasks={tasks}
        loading={isLoading}
        onStart={handleStart}
        onCancel={handleCancel}
        onRetry={handleRetry}
      />

      <CreateTaskModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
      />
    </div>
  )
}

export default CollectionTaskListPage
